const chalk = require('chalk')
const path = require('path')
const { getRequest, mkdirsSync } = require('../script/common')
const { runCommand } = require('./runCommand')

/**
 * 克隆项目到本地
 * @param {*} giteePushInfo // gitee WebHook的回调参数
 * @returns clonePath 克隆的本地项目目录地址
 */
module.exports = (giteePushInfo) => {
  console.log(chalk.blue('\n开始拉取项目-------------------------------'))

  // 拉取远程项目到本地
  let strArr = giteePushInfo.ref.split('/')
  let branch = strArr[strArr.length - 1]
  let clonePath = `${path.join(__dirname, '../../')}/project/${giteePushInfo.project.name}/${branch}`

  // 获取commit中?后的数据
  let commitData = getRequest(giteePushInfo.head_commit.message)
  let isInstall = false
  if (commitData && commitData.install && commitData.install == 1) {
    isInstall = commitData.install
  }

  // 分支拦截 只有指定分支才会触发
  if (!['tmt', 'beta'].includes(branch)) {
    console.log(chalk.red(`不能拉取当前分支${branch}}`));
    return false
  }

  // 创建项目文件夹
  mkdirsSync(clonePath)

  // 运行拉取项目到sh脚本
  runCommand(`sh ${path.join(__dirname, '../shell/cloneProject.sh')} ${clonePath} ${branch} ${giteePushInfo.project.git_ssh_url} ${isInstall ? 1 : 0}`)

  console.log(chalk.blue('项目拉取完成-------------------------------'))
  return clonePath
}